<script setup>
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'

const dataL = ref({
  firstOrder: [
    { name: '电', id: 1 },
    { name: '水', id: 2 },
    { name: '气', id: 3 }
  ],
  secondLevel: [
    { name: '分支', id: 11 },
    { name: '建筑', id: 12 },
    { name: '工序', id: 13 },
    { name: '批次', id: 14 },
    { name: '工序', id: 15 }
  ],
  treeVal: [
    {
      label: 'Level one 1',
      children: [
        {
          label: 'Level two 1-1',
          children: [
            {
              label: 'Level three 1-1-1'
            }
          ]
        }
      ]
    },
    {
      label: 'Level one 2',
      children: [
        {
          label: 'Level two 2-1',
          children: [
            {
              label: 'Level three 2-1-1'
            }
          ]
        },
        {
          label: 'Level two 2-2',
          children: [
            {
              label: 'Level three 2-2-1'
            }
          ]
        }
      ]
    },
    {
      label: 'Level one 3',
      children: [
        {
          label: 'Level two 3-1',
          children: [
            {
              label: 'Level three 3-1-1'
            }
          ]
        },
        {
          label: 'Level two 3-2',
          children: [
            {
              label: 'Level three 3-2-1'
            }
          ]
        }
      ]
    }
  ]
})

const activeF = ref(0)
const firstClick = (id) => {
  activeF.value = id
}
const activeS = ref(0)
const secondClick = (id) => {
  activeS.value = id
}

const treeRef = ref()
const defaultProps = {
  children: 'children',
  label: 'label'
}
const handleNodeClick = (data) => {
  console.log(data)
}
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

// 右侧表单
const formInline = ref({
  startTime: '',
  endTime: ''
})
const checkedY = ref(false)
const onChangeY = (status) => {
  checkedY.value = status
}
const checkedM = ref(false)
const onChangeM = (status) => {
  checkedM.value = status
}
const checkedD = ref(false)
const onChangeD = (status) => {
  checkedD.value = status
}
const checkedT = ref(false)
const onChangeT = (status) => {
  checkedT.value = status
}
const checkedH = ref(false)
const onChangeH = (status) => {
  checkedH.value = status
}
const onSubmit = () => {
  console.log('submit!')
}
//echarts图表
const setUpEcharts = () => {
  const chartDom = document.querySelector('.mainE')
  const myChart = echarts.init(chartDom)
  const rawData = [
    [100, 302, 301, 334, 390, 330, 320],
    [320, 132, 101, 134, 90, 230, 210],
    [220, 182, 191, 234, 290, 330, 310],
    [150, 212, 201, 154, 190, 330, 410]
  ]
  const totalData = []
  for (let i = 0; i < rawData[0].length; ++i) {
    let sum = 0
    for (let j = 0; j < rawData.length; ++j) {
      sum += rawData[j][i]
    }
    totalData.push(sum)
  }
  const grid = {
    left: 100,
    right: 100,
    top: 50,
    bottom: 50
  }
  const series = ['尖', '峰', '平', '谷'].map((name, sid) => {
    return {
      name,
      type: 'bar',
      stack: 'total',
      barWidth: '60%',
      label: {
        show: true,
        formatter: (params) => Math.round(params.value * 1000) / 10 + '%'
      },
      data: rawData[sid].map((d, did) => (totalData[did] <= 0 ? 0 : d / totalData[did]))
    }
  })
  const option = {
    legend: {
      selectedMode: false
    },
    grid,
    yAxis: {
      type: 'value'
    },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    series
  }
  option && myChart.setOption(option)
}
const pieLEcharts = () => {
  const chartDom = document.querySelector('.mainPL')
  const myChart = echarts.init(chartDom)
  const option = {
    title: {
      text: '分时电量：尖、峰、平、谷占比',
      subtext: '',
      right: '0',
      top: '0'
    },
    color: [
      '#669933',
      '#ff9966',
      '#ff99cc',
      '#ef5aa1',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ],

    series: [
      {
        name: '分时电量',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '尖' },
          { value: 735, name: '峰' },
          { value: 580, name: '平' },
          { value: 484, name: '谷' }
        ],
        labelLine: {
          show: false
        },
        label: {
          show: false
        }
      }
    ]
  }
  option && myChart.setOption(option)
}
const pieREcharts = () => {
  const chartDom = document.querySelector('.mainPR')
  const myChart = echarts.init(chartDom)
  const option = {
    title: {
      text: '分时电量：尖、峰、平、谷占比',
      subtext: '',
      right: '0',
      top: '0'
    },
    color: [
      '#669933',
      '#ff9966',
      '#ff99cc',
      '#ef5aa1',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ],

    series: [
      {
        name: '分时电量',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '尖' },
          { value: 735, name: '峰' },
          { value: 580, name: '平' },
          { value: 484, name: '谷' }
        ],
        labelLine: {
          show: false
        },
        label: {
          show: false
        }
      }
    ]
  }
  option && myChart.setOption(option)
}
onMounted(() => {
  pieLEcharts()
  pieREcharts()
  setUpEcharts()
})

// table
const tableData = ref([
  {
    id: 1,
    node: '节点1',
    date: '2023-04-01',
    period: 1234,
    same: 1100,
    onYear: '增长20%'
  },
  {
    id: 2,
    node: '节点2',
    date: '2023-04-02',
    period: 5678,
    same: 5500,
    onYear: '下降10%'
  },
  {
    id: 3,
    node: '节点3',
    date: '2023-04-03',
    period: 3456,
    same: 3300,
    onYear: '增长5%'
  }
  // 根据需要添加更多数据
])
const getSummaries = (param) => {
  const { data } = param
  // 初始化需要计算的列
  const sums = []
  let totalPeriod = 0
  let totalSame = 0

  // 计算本期和同期的总和
  data.forEach((item) => {
    totalPeriod += Number(item.period) || 0
    totalSame += Number(item.same) || 0
  })

  // 计算同比（处理除零异常）
  const calcOnYear = () => {
    if (totalSame === 0) return '-'
    return (((totalPeriod - totalSame) / totalSame) * 100).toFixed(2) + '%'
  }

  // 处理每一列数据
  param.columns.forEach((column, index) => {
    switch (column.property) {
      case 'node':
        sums[index] = '合计'
        break
      case 'date':
        sums[index] = '—' // 特殊符号占位
        break
      case 'period':
        sums[index] = totalPeriod.toLocaleString() // 添加千分位分隔符
        break
      case 'same':
        sums[index] = totalSame.toLocaleString()
        break
      case 'onYear':
        sums[index] = calcOnYear()
        break
      default:
        sums[index] = '—'
    }
  })

  return sums
}
</script>

<template>
  <div class="test">
    <div class="testL">
      <!-- 类别 -->
      <div class="LFirst">
        <div class="LFtitle">类别:</div>
        <div class="LFvalue Lvalue">
          <div
            v-for="item in dataL.firstOrder"
            :key="item.id"
            class="LFitem Litem"
            :class="{ active: item.id === activeF }"
            @click="firstClick(item.id)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <!-- 标签 -->
      <div class="LFirst">
        <div class="LFtitle">标签:</div>
        <div class="LFvalue Lvalue">
          <div
            v-for="item in dataL.secondLevel"
            :key="item.id"
            class="LFitem Litem"
            :class="{ active: item.id === activeS }"
            @click="secondClick(item.id)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <hr />
      <div class="LTree">
        <div class="Linput">
          <el-input v-model="filterText" style="width: 240px" placeholder="筛选关键字" />
        </div>
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="dataL.treeVal"
          :props="defaultProps"
          @node-click="handleNodeClick"
          default-expand-all
          :filter-node-method="filterNode"
        />
      </div>
    </div>
    <div class="testR">
      <div class="rTop">
        <div class="rForm">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="formInline.startTime"
                type="date"
                placeholder="开始时间"
                clearable
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="formInline.endTime"
                type="date"
                placeholder="结束时间"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-check-tag :checked="checkedD" @change="onChangeD">日</el-check-tag>
            </el-form-item>
            <el-form-item>
              <el-check-tag :checked="checkedM" @change="onChangeM">月</el-check-tag>
            </el-form-item>
            <el-form-item>
              <el-check-tag :checked="checkedY" @change="onChangeY">年</el-check-tag>
            </el-form-item>
            <el-form-item>
              <el-check-tag :checked="checkedT" type="success" @change="onChangeT"
                >同比</el-check-tag
              >
            </el-form-item>
            <el-form-item>
              <el-check-tag :checked="checkedH" type="success" @change="onChangeH"
                >环比</el-check-tag
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="rCenter">
        <div class="pieT">
          <div class="mainPL"></div>
          <div class="mainPR"></div>
        </div>
        <div class="barB">
          <div class="mainE"></div>
        </div>
      </div>
      <div class="rBottom">
        <div class="rTable">
          <el-table
            :data="tableData"
            :summary-method="getSummaries"
            show-summary
            border
            style="width: 100%"
          >
            <el-table-column prop="node" label="节点" width="180" />
            <el-table-column prop="date" label="时间" width="180" />
            <el-table-column prop="period" label="本期" />
            <el-table-column prop="same" label="同期" />
            <el-table-column prop="onYear" label="同比" />
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.test {
  display: flex;
  width: 100%;
  height: 100%;
  .testL {
    padding: 20px;
    width: 20%;
    font-size: 14px;
    background: #f2f2f2;
    .LFirst {
      display: flex;
      .LFtitle {
        width: 55px;
      }
      .LFvalue {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        .LFitem {
          margin: 0 10px;
          margin-bottom: 10px;
          padding: 3px 15px;
          border-radius: 5px;
          background: #d7d7d7;
          cursor: pointer;
        }
        .active {
          background: #6699ff;
        }
      }
    }
    .Linput {
      margin-top: 10px;
      margin-bottom: 10px;
      width: 100%;
    }
  }
  .testR {
    flex: 1;
    padding: 20px;
    .rCenter {
      height: 450px;
      .pieT {
        display: flex;
        width: 100%;
        height: 30%;
        .mainPL {
          width: 50%;
        }
        .mainPR {
          width: 50%;
        }
      }
      .barB {
        height: 70%;
        .mainE {
          height: 100%;
        }
      }
    }
  }
}
.el-tree {
  background-color: transparent;
}
</style>
